import BaseHTTPServer
import telnetlib

get_list = [
    # admin commands
    "outputs",
    # database commands
    "find",
    "list",
    "listall",
    "lsinfo",
    "search",
    # playlist commands
    "currentsong",
    "playlistinfo",
    "playlistid",
    "plchanges",
    "plchangesposid",
    # miscellaneous commands
    "commands",
    "notcommands",
    "ping",
    "stats",
    "status"
    ]

post_list = [
    # admin commands
    "disableoutput",
    "enableoutput",
    "kill",
    "update",
    # playlist commands
    "add",
    "clear",
    "delete",
    "deleteid",
    "load",
    "move",
    "moveid",
    "rm",
    "save",
    "shuffle",
    "swap",
    "swapid",
    # playback commands
    "crossfade",
    "next",
    "pause",
    "play",
    "playid",
    "previous",
    "random",
    "repeat",
    "seek",
    "seekid",
    "setvol",
    "stop",
    # miscellaneous commands
    "clearerror",
    "close",
    "password"
    ]

class InvalidPath(Exception):
    "An exception raised at an invalid path"

def _get_arg_list(path):
    path = path[:].replace("%20"," ")
    command_index = path.find("mpd/")

    if command_index == -1: raise InvalidPath

    args = path[command_index + 4:].split("?")
    args = [args[0]] + ['"' + arg + '"' for arg in args[1:]]
    return args

class RestMPDHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    server_version = "RestMPD/0.1"

    def do_command(self, supported_list):
        mpd_connection = telnetlib.Telnet("localhost", 6600)
        mpd_connection.expect(["OK.*\\n"])[2]
        
        try:
            args = _get_arg_list(self.path)

            if args[0] in supported_list:
                
                mpd_connection.write(' '.join(args) + "\n")
                print ' '.join(args) + "\n"
                
                # return_status depends on order of regular expressions
                # in expect call. DO NOT CHANGE.
                return_status, match ,response = mpd_connection.expect(
                    ["OK\\n", "ACK(.*)\\n"]
                )
                
                print return_status
                print response
                
                if return_status == 0:
                    self.send_response(200, "Command successful")
                    self.end_headers()
                    self.wfile.write(response)
                elif return_status == 1:
                    print match.groups()[0]
                    self.send_error(400, match.groups()[0])
            
            else:
                self.send_error(404, "Command not supported by HTTP method")

        except InvalidPath:
            self.send_error(404, "Bad path")

    def do_GET(self):

        self.do_command(get_list)

    def do_POST(self):
        self.do_command(post_list)


server = BaseHTTPServer.HTTPServer(('', 6680), RestMPDHandler)
server.serve_forever()

try:
    g_mpd_socket.close()
except:
    print "could not close mpd socket..."
